﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Linq.Expressions;
using System.Web.Routing;

namespace FoundationLib.Web.Mvc
{
	public static class DropDownHelper
	{
		public static MvcHtmlString EnumDropDownList(this HtmlHelper htmlHelper, Type enumType, object selectedValue, 
			IDictionary<string, object> htmlProperties)
		{
			if (enumType == null || !enumType.IsEnum)
				return MvcHtmlString.Empty;

			TagBuilder selectBuilder = new TagBuilder("select");
			if (htmlProperties != null)
				selectBuilder.MergeAttributes(htmlProperties);

			string[] names = Enum.GetNames(enumType);
			string selectedName = selectedValue as string;

			for (int i = 0; i < names.Length; i++)
			{
				TagBuilder optionBuilder = new TagBuilder("option");
				optionBuilder.MergeAttribute("value", names[i]);
				if (selectedValue != null && names[i] == selectedName)
					optionBuilder.MergeAttribute("selected", "selected");
				optionBuilder.SetInnerText(names[i]);
				selectBuilder.InnerHtml += optionBuilder.ToString();
			}

			return MvcHtmlString.Create(selectBuilder.ToString());
		}

		public static MvcHtmlString EnumDropDownList(this HtmlHelper htmlHelper, Type enumType, object selectedValue, 
			object htmlProperties)
		{
			return EnumDropDownList(htmlHelper, enumType, selectedValue, 
				htmlProperties != null ? new RouteValueDictionary(htmlProperties) : null);
		}

		public static MvcHtmlString EnumDropDownList(this HtmlHelper htmlHelper, Type enumType, object selectedValue)
		{
			return EnumDropDownList(htmlHelper, enumType, selectedValue, null);
		}

		public static MvcHtmlString EnumDropDownList(this HtmlHelper htmlHelper, Type enumType)
		{
			return EnumDropDownList(htmlHelper, enumType, null);
		}
	}
}
